package com.utf999.qiangmanger.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.utf999.qiangmanger.dao.iface.IAdminUserDAO;
import com.utf999.qiangmanger.entity.orm.AdminUserEntity;
import com.utf999.qiangmanger.entity.orm.CompanyEntity;
import com.utf999.qiangmanger.entity.orm.StorefrontEntity;
import com.utf999.qiangmanger.exception.AuthenticationException;
import com.utf999.qiangmanger.exception.BizException;
import com.utf999.qiangmanger.exception.ResponseCode;
import com.utf999.qiangmanger.service.AbstractService;
import com.utf999.qiangmanger.service.iface.IAdminUserService;
import com.utf999.qiangmanger.service.iface.IStorefrontService;
import com.utf999.qiangmanger.service.iface.redis.IRedisOnlineUserService;
import com.utf999.qiangmanger.utils.MD5Utils;
import com.utf999.qiangmanger.utils.TokenUtils;

/**
 * @author yinwenjie
 */
@Component("AdminUserServiceImpl")
public class AdminUserServiceImpl extends AbstractService<AdminUserEntity, IAdminUserDAO> implements IAdminUserService {

	/**
	 * 
	 */
	@Autowired
	private IAdminUserDAO adminUserDAO;
	
	/**
	 * 
	 */
	@Autowired
	private IStorefrontService storefrontService;
	
	/**
	 * 
	 */
	@Autowired
	private IRedisOnlineUserService redisOnlineUserService;
	
	/* (non-Javadoc)
	 * @see com.utf999.qiangmanger.service.iface.IAdminUserService#consoleUserLogon(java.lang.String, java.lang.String)
	 */
	@Override
	public String consoleUserLogon(String userName, String password) throws AuthenticationException {
		if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
			throw new AuthenticationException();
		}
		
		/*
		 * 1、首先查询用户信息
		 * 2、然后对比密码
		 * 3、首先从redis中查询这个用户是否已经有token信息了，如果有，则重用就行了
		 * 4、如果用户名和密码都匹配，则为用户生成一个全系统唯一的token信息（保存到redis中）；
		 * 反之重新跳转到登录页面
		 * */
		//1、==============
		AdminUserEntity adminUser = null;
		try {
			adminUser = this.queryAdminUser(userName);
		} catch (BizException e) {
			throw new AuthenticationException();
		}
		if(adminUser == null) {
			throw new AuthenticationException();
		}
		
		//2、==============验证密码
		String encodePassword = adminUser.getEncodePassword();
		String newEncodePassword = MD5Utils.encoder(password);
		if(!StringUtils.equals(encodePassword , newEncodePassword)) {
			throw new AuthenticationException();
		}
		
		//2.1、============更新这个用户的最后登录时间
		Date logonTime = new Date();
		adminUser.setLastlogTime(logonTime);
		this.update(adminUser);
		
		//3、==============重新查询是否有token存在
		String device = "web";
		String oldToken;
		try {
			oldToken = this.redisOnlineUserService.getTokenByUserinfo(userName, device);
		} catch (BizException e1) {
			throw new AuthenticationException();
		}
		if(!StringUtils.isEmpty(oldToken)) {
			return oldToken;
		}
		
		//4、==============生成token（注意登录的设备默认都为web）
		String newToken;
		try {
			newToken = TokenUtils.generateUUID(adminUser.getUid(), "web", logonTime);
			this.redisOnlineUserService.registUser(adminUser.getUserName(), device, newToken);
		} catch (BizException e) {
			throw new AuthenticationException();
		}
		return newToken;
	}
	
	/* (non-Javadoc)
	 * @see com.utf999.qiangmanger.service.iface.IAdminUserService#appendSuperAdminuser(java.lang.String, java.lang.String)
	 */
	@Override
	public AdminUserEntity appendSuperAdminuser(String username, String password) throws BizException {
		if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			throw new BizException("错误的参数信息，请检查！", ResponseCode.E403);
		}
		
		AdminUserEntity adminUser = new AdminUserEntity();
		adminUser.setUserName(username);
		//超级管理员，级别是1
		adminUser.setAdminLevel(1);
		adminUser.setEncodePassword(MD5Utils.encoder(password));
		adminUser.setJoinTime(new Date());
		//最后登录时间
		Date lastlogTime = new Date();
		lastlogTime.setTime(0l);
		adminUser.setLastlogTime(lastlogTime);
		adminUser.setStatus(1);
		
		//进行添加
		this.insert(adminUser);
		return adminUser;
	}
	
	/* (non-Javadoc)
	 * @see com.utf999.qiangmanger.service.iface.IAdminUserService#appendStoreAdminuser(java.lang.String, java.lang.String, java.lang.Integer, java.lang.String)
	 */
	@Override
	public AdminUserEntity appendStoreAdminuser(String username, String password, Integer adminlevel, String storeid) throws BizException {
		if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)
			||  adminlevel == null || StringUtils.isEmpty(storeid)) {
			throw new BizException("错误的参数信息，请检查！", ResponseCode.E403);
		}
		if((adminlevel == 3 || adminlevel == 4) && StringUtils.isEmpty(storeid)) {
			throw new BizException("添加门店管理员/收银管理员，必须指定店面编号！", ResponseCode.E403);
		}
			
		AdminUserEntity adminUser = new AdminUserEntity();
		adminUser.setUserName(username);
		adminUser.setAdminLevel(adminlevel);
		adminUser.setEncodePassword(MD5Utils.encoder(password));
		adminUser.setJoinTime(new Date());
		//最后登录时间
		Date lastlogTime = new Date();
		lastlogTime.setTime(0l);
		adminUser.setLastlogTime(lastlogTime);
		adminUser.setStatus(1);
		
		//当门店信息管理员或者收银管理员时，才能进行店面和公司关联的添加
		if(adminlevel == 3 || adminlevel == 4) {
			StorefrontEntity storefront = (StorefrontEntity)this.storefrontService.getEntity(storeid);
			if(storefront == null) {
				throw new BizException("没有找到指定的店面信息，请检查 ！", ResponseCode.E401);
			}
			CompanyEntity company = storefront.getCompany();
			if(company == null) {
				throw new BizException("没有找到指定的公司信息，请检查 ！", ResponseCode.E401);
			}
			adminUser.setStorefront(storefront);
			adminUser.setCompany(company);
		}
		
		//进行添加
		this.insert(adminUser);
		return adminUser;
	}

	/* (non-Javadoc)
	 * @see com.utf999.qiangmanger.service.iface.IAdminUserService#appendCompanyAdminuser(java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public AdminUserEntity appendCompanyAdminuser(String username, String password, String companyid) throws BizException {
		if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)
			|| StringUtils.isEmpty(companyid)) {
			throw new BizException("错误的参数信息，请检查！", ResponseCode.E403);
		}
			
		AdminUserEntity adminUser = new AdminUserEntity();
		adminUser.setUserName(username);
		//公司管理员的级别是2
		adminUser.setAdminLevel(2);
		adminUser.setEncodePassword(MD5Utils.encoder(password));
		adminUser.setJoinTime(new Date());
		//最后登录时间
		Date lastlogTime = new Date();
		lastlogTime.setTime(0l);
		adminUser.setLastlogTime(lastlogTime);
		adminUser.setStatus(1);
		
		//关联公司id即可
		CompanyEntity company = new CompanyEntity();
		company.setUid(companyid);
		adminUser.setCompany(company);
		
		//进行添加
		this.insert(adminUser);
		return adminUser;
	}
	
	/* (non-Javadoc)
	 * @see com.utf999.qiangmanger.service.iface.IAdminUserService#modifyAdminuserPassword(java.lang.String, java.lang.String)
	 */
	@Override
	public void modifyAdminuserPassword(String adminid, String password) throws BizException {
		if(StringUtils.isEmpty(adminid) || StringUtils.isEmpty(password)) {
			throw new BizException("错误的参数信息，请检查！", ResponseCode.E403);
		}
		
		AdminUserEntity adminuser = (AdminUserEntity)this.adminUserDAO.getEntity(adminid);
		if(adminuser == null) {
			throw new BizException("没有找到指定管理员用户！", ResponseCode.E501);
		}
		
		adminuser.setEncodePassword(MD5Utils.encoder(password));
		this.adminUserDAO.update(adminuser);
	}
	
	/* (non-Javadoc)
	 * @see com.utf999.qiangmanger.service.iface.IAdminUserService#modifyUserStatus(java.lang.String)
	 */
	@Override
	public void modifyUserStatus(String adminid) throws BizException {
		if(StringUtils.isEmpty(adminid)) {
			throw new BizException("错误的参数信息，请检查！", ResponseCode.E403);
		}
		AdminUserEntity adminuser = (AdminUserEntity)this.adminUserDAO.getEntity(adminid);
		if(adminuser == null) {
			throw new BizException("没有找到指定管理员用户！", ResponseCode.E501);
		}
		
		if(adminuser.getStatus() == 1) {
			adminuser.setStatus(0);
		} else {
			adminuser.setStatus(1);
		}
		this.adminUserDAO.update(adminuser);
	}
	
	/* (non-Javadoc)
	 * @see com.utf999.qiangmanger.service.iface.IAdminUserService#queryAdminUser(java.lang.String)
	 */
	@Override
	public AdminUserEntity queryAdminUser(String userName) throws BizException {
		if(StringUtils.isEmpty(userName)) {
			throw new BizException("传入的用户名参数错误，请检查！", ResponseCode.E404);
		}
		
		return this.adminUserDAO.queryAdminUser(userName);
	}
	
	/* (non-Javadoc)
	 * @see com.utf999.qiangmanger.service.AbstractService#getBaseDAO()
	 */
	@Override
	protected IAdminUserDAO getBaseDAO() {
		return this.adminUserDAO;
	}
	
	/* (non-Javadoc)
	 * @see com.utf999.qiangmanger.service.iface.IAdminUserService#queryAdminByStore(java.lang.String, java.lang.Integer)
	 */
	@Override
	public List<AdminUserEntity> queryAdminByStore(String storeid , Integer status) throws BizException {
		if(StringUtils.isEmpty(storeid)) {
			return null;
		}
		
		return this.adminUserDAO.queryAdminByStore(storeid , status);
	}
	
	/* (non-Javadoc)
	 * @see com.utf999.qiangmanger.service.iface.IAdminUserService#queryAdmingByToken(java.lang.String)
	 */
	@Override
	public AdminUserEntity queryAdmingByToken(String token) throws BizException {
		if(StringUtils.isEmpty(token)) {
			throw new BizException("token参数错误，请检查！", ResponseCode.E501);
		}
		
		String usernameAndDevice = this.redisOnlineUserService.getUserinfoByToken(token);
		if(StringUtils.isEmpty(usernameAndDevice)) {
			throw new BizException("没有找到对应的token信息，请检查！", ResponseCode.E501);
		}
		
		//分解出username，并且查询数据库
		int index = usernameAndDevice.lastIndexOf(",");
		String username = usernameAndDevice.substring(0, index);
		AdminUserEntity user = this.adminUserDAO.queryAdminUser(username);
		return user;
	}

	/* (non-Javadoc)
	 * @see com.utf999.qiangmanger.service.iface.IAdminUserService#querySuperAdmin(java.lang.Integer)
	 */
	@Override
	public List<AdminUserEntity> querySuperAdmin(Integer status) throws BizException {
		return this.adminUserDAO.querySuperAdmin(status);
	}

	/* (non-Javadoc)
	 * @see com.utf999.qiangmanger.service.iface.IAdminUserService#queryCompanyAdmin(java.lang.String)
	 */
	@Override
	public List<AdminUserEntity> queryCompanyAdmin(String companyid) throws BizException {
		if(StringUtils.isEmpty(companyid)) {
			throw new BizException("参数错误，请检查！", ResponseCode.E501);
		}
		
		return this.adminUserDAO.queryCompanyAdmin(companyid);
	}
}
